<template>
    <el-container style="height:100dvh;">
        <el-asdie>
            <div class="prPictureBox"></div>
        </el-asdie>
        <el-main>
   
            <div class="solgan">
                <span  class="solganText">Hello !<br/>欢迎注册</span>
            </div>
            <div class="login">
                <div class="account">
                    <div style="display: flex;">
                        <el-input class="account" 
                            :maxlength="11" 
                            ref="account" 
                            v-model="phoneNumVal" 
                            placeholder="输入手机号"
                            @focus="phoneFocus"
                            @blur="phoneLostFocus"
                            required
                        ></el-input>
                        <el-button class="veriCodeButtonDisable" v-if="phoneError">验证码</el-button>
                        <el-button class="veriCodeButtonEnable" v-else-if="!downCountFrezz" @click=" applyVeriCode">验证码</el-button>
                        <el-button v-else class="veriCodeButtonDisable">验证码{{downCount}}</el-button>
                    </div>
                    <div style="display: flex;">
                        <span style="display: flex;" class="is-error" v-if="phoneError && phoneActive">请输入正确的手机号</span>
                    </div>
                </div>
                
                <div class="veriCode">
                    <el-input class="veriCode" 
                    ref="veriCode" v-model="veriCodeVal" 
                    placeholder="输入验证码" 
                    :maxlength="6"
                    @focus="vericodeFocus"
                    @blur="vericodeLostFocus"
                    required
                    ></el-input>
                    <span class="is-error" v-if="vericodeError && vericodeActive">验证码是6位数字</span> 
                </div>

                <div class="passwd">
                    <el-input class="passwd" 
                    ref="passwd" v-model="passWordVal" 
                    placeholder="输入密码" 
                    type="password" show-password
                    :maxlength="10"
                    required
                    @focus="passwordFocus"
                    @blur="passwordLostFocus">密码</el-input>
                    <span class="is-error" v-if="passwdError && passwdActive">密码不少于8位，包含数字和大小写字母</span> 
                </div>
                
                <el-checkbox v-model="isChecked" @change="handleCheckboxChange" class="privacy"><router-link  class="documentLink" :to="{name:'UserPolicy'}">用户协议</router-link>和<router-link  class="documentLink" :to="{name:'PrivatePolicy'}">隐私政策</router-link></el-checkbox>
                <el-button v-if="isChecked" class="registEnable" @click="post_regist">注册</el-button>
                <el-button v-else  class="registDisable">注册</el-button>
                
            </div>
        </el-main>
    </el-container>

</template>

<script>
import axios from 'axios';
import { ElNotification } from 'element-plus';
export default{
    name:'RegistPage',
    data(){
        return{
            phoneNumVal:'',
            passWordVal:'',
            veriCodeVal:'',
            recommender:null,
            referee:null,

            phoneRegex: /^1[3456789]\d{9}$/, // 电话号码的正则表达式
            passwdRegex:/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$/,//密码强度正则
            veriCodeRegex:/^[0-9]{6}$/,//验证码为6位数字
            
            isChecked:false,
            
            phoneActive:false,
            passwdActive:false,
            vericodeActive:false,
            
            downCount:60,
            downCountFrezz:false,
            timer:null,
        };
    },
    mounted(){
        console.log("注册页url参数： "+this.$route.query.rcode);
        this.recommender=this.$route.query.rcode;
    },
    computed:{
        isButtonDisabled(){
            return !this.isChecked;
        },
        phoneError(){
            console.log(this.phoneRegex.test(this.phoneNumVal));
            return !this.phoneRegex.test(this.phoneNumVal);
        },
        passwdError(){
            console.log(this.passwdRegex.test(this.passWordVal));
            return !this.passwdRegex.test(this.passWordVal);
        },
        vericodeError(){
            return !this.veriCodeRegex.test(this.veriCodeVal);
        }

    },
    methods:{
        phoneFocus(){
            this.phoneActive=true;
        },
        phoneLostFocus(){
            this.phoneActive=false;
        },
        passwordFocus(){
            this.passwdActive=true;
        },
        passwordLostFocus(){
            this.passwdActive=false;
        },
        vericodeFocus(){
            this.vericodeActive=true;
        },
        vericodeLostFocus(){
            this.vericodeActive=false;
        },
        applyVeriCode(){
            this.downCountFrezz=true;
        
            //倒计时
            this.timer=setInterval(()=>{
                this.downCount--;
                if(this.downCount<=0){
                    console.log(this.downCount);
                    clearInterval(this.timer)
                    this.downCount=60;
                    this.downCountFrezz=false;
                }
            },1000);
            //调用生成验证码
            this.getVeriCode(this.phoneNumVal)
        },
        async getVeriCode(phoneNum){
            try{
                    //await axios.get("/getwords?letter="+this.$route.params.letter,{withCredentials:true})
                    await axios.get("/api/getvericode/",
                    {params:{
                    phone:phoneNum,
                    }},
                    {withCredentials:true})
                    .then(response=>
                    {
                    try {
                            const data = JSON.parse(response.data);
                            if(data){
                                console.log("注册验证码信息："+JSON.stringify(data));
                                ElNotification({
                                    message:data[0]['msg'],
                                    title:'获取验证码',
                                    type:'info',
                                    duration:3000,
                                })
                            }
                        } catch (error) {
                        console.error(error);
                    }
                })
            }
            catch(error){
            console.log(error);
        }
        },

       async post_regist(){
            //console.log(this.phoneNumVal+"@"+this.veriCodeVal)
            if(this.phoneNumVal=="" || this.veriCodeVal==""){
                ElNotification({
                        message:'请确认手机号、验证码和密码都已经填写了信息',
                        title:'用户注册',
                        type:'info',
                        duration:3000,
                    })
            }else{  // 如果字段都有值调接口
                const data={
                            phone:this.phoneNumVal,
                            vericode:this.veriCodeVal,
                            password:this.passWordVal,
                            recommender:this.recommender,
                        };
                //console.log(JSON.stringify(data));
                //调创建用户的接口创建新用户
                await axios.post("/api/user_regist/",data,{withCredentials:true})
                        .then(response=>
                        {
                            try{
                                if(response.data){ 
                                    console.log(response.data['msg']);
                                    ElNotification({
                                    message:response.data['msg'],
                                    title:response.data['code'],
                                    type:'info',
                                    duration:3000,
                                    });
                                    //如果后端创建用户成功，执行页面跳转
                                    if(response.data['code']==20000){
                                        console.log("url: "+(response.data['data'][0].url));
                                        this.referee=response.data['data'][0].uid;
                                        const redirect_url=response.data['data'][0].url;
                                        console.log("url: "+redirect_url);
                                        //如果当前浏览器注册过新用户，那么要把cookie都删掉，防止新用户进老用户的界面
                                        this.$commonFunctions.deleteCookie("user_id");
                                        this.$commonFunctions.deleteCookie("pcode");
                                        this.$commonFunctions.deleteCookie("user_name");
                                        this.$commonFunctions.deleteCookie("avatar");
                                        this.$commonFunctions.deleteCookie("login_token");
                                        this.$router.push({path:`${redirect_url}`});
                                    }
                                }
                            }
                            catch(error){
                                console.log(error)
                            }
                        });
                // //如果用户是被推荐来的，创建完成之后调用绑定关系接口，把新用户和推荐人绑定起来。
                // //这个关系会保存在redis里，新用户激活给推荐人发放完奖励之后就会删除
                // console.log("推荐人rcode："+this.recommender)
                // if(this.recommender!==null&&this.recommender!==undefined){
                //     console.log("推荐人："+this.recommender+" 被推荐人："+this.referee)
                //     const relation={
                //     'recommender':this.recommender,  //推荐人rcode
                //     'referee':this.referee,} //被推荐人id}
                //     await axios.post("/api/bind_recommendation_relationship/",relation,{withCredentials:true})
                //         .then(response=>
                //         {
                //             try{   
                                
                //                 if(response.data['code']==20000){
                //                     console.log("url: "+(response.data['msg']));
                //                 }else{
                //                     ElNotification({
                //                         message:response.data['msg'],
                //                         title:response.data['code'],
                //                         type:'info',
                //                         duration:3000,
                //                         });
                //                 }
                //             }
                //             catch(error){
                //                 console.log(error)
                //             } 
                //         });
                // }
            }
        },
    }
      
    }
</script>

<style scoped>
.documentLink{
    text-decoration: none;
}

.el-input.account.account{
  flex: 70%;
}

.el-button.veriCodeButtonEnable{
    margin-left: 10px;
    background-color:#2a55e2 ;
    color: #fff;
}

.el-button.veriCodeButtonDisable{
    margin-left: 10px;
    background-color:#f4f4f5 ;
    color: #909399;
}

div.account{
    margin-bottom: 2dvh;
    display: flex;
    flex-direction: column;
}
div.passwd{
    margin-bottom: 2dvh;
}
div.veriCode{
    margin-bottom: 2dvh;
}
.is-error{
   font-size: small;
   font-weight: 300;
   color:red;
   display: block;
   margin: 0;
}
button.el-button.registEnable{
    margin-top: 7dvh;
    display: block;
    width: 22.5dvw;
    font-weight: 600;
    background-color:#2a55e2 ;
    color: #fff;
}

button.el-button.registDisable{
    margin-top: 7dvh;
    display: block;
    width: 22.5dvw;
    font-weight: 600;
    background-color:#f4f4f5 ;
    color: #909399;
}

div.prPictureBox{
    background-image:url('https://sam-test.oss-cn-beijing.aliyuncs.com/assets/loginbkimg%40170%20(1).png') ;
    background-repeat: no-repeat;
    background-size: cover;
    width: 67.5dvw;
    height: 100dvh;
}

div.solgan{
    height: 25dvh;
    margin-top:8.2dvh;
    padding-left: 3dvw;
    text-align: left;
    font-size: 15px;
    color: rgba(0,0,0,0.65);
    font-weight: 500;
}

div.login{
    margin:8.2dvh auto;
    padding-left: 3dvw;
    padding-right: 3dvw;
    text-align: left;
    font-size: 15px;
    color: rgba(0,0,0,0.65);
    font-weight: 500;
}

span.solganText{
    display: block;
    padding-bottom: 2dvh;
    color: #2245ba;
    font-size: 22pt;
    font-weight: bolder;
}

</style>